package buddhi.main.MyTour;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import buddhi.main.MyTour.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author Buddhiprabha
 *
 */

public class OpenGallery extends Activity{
	
	public Integer[] allImageNames = {};		//array to store IDs of all images of all preferences
	public String[] finalGallery = {};			//array to store names of all images of all preferences
	public String[] finalGalleryDesc = {};		//array to store descriptions of all images of all preferences
	@SuppressWarnings("rawtypes")
	private List selectedPlacesList = new ArrayList();
	@SuppressWarnings({ "unused", "rawtypes" })
	private List lotsAndLas = new ArrayList();
	public String[] selectedPlacesArray = {};
	
	ImageView i;
	
	private String[] historicalImageNames={		//names of historically valued places
			"http://mytoursrilanka.eway.asia.lk/images/stories/anuradhapura.jpg",
			"http://mytoursrilanka.eway.asia.lk/images/stories/polonnaruwa.jpg",
			"http://mytoursrilanka.eway.asia.lk/images/stories/daladamaligawa.jpg",
			"http://mytoursrilanka.eway.asia.lk/images/stories/koneshwaram.jpg",
			"http://mytoursrilanka.eway.asia.lk/images/stories/dambulla.jpg"
    };
	
	private String[] entertainmentImageNames={	//names of entertaining places
			"http://mytoursrilanka.eway.asia.lk/images/stories/arugambay.jpg",
    		"http://mytoursrilanka.eway.asia.lk/images/stories/bolgodalake.jpg",
    	    "http://mytoursrilanka.eway.asia.lk/images/stories/hanwellarocks.jpg",
    	    "http://mytoursrilanka.eway.asia.lk/images/stories/kithulgala.jpg"
    };
	
	private String[] naturalImageNames={		//names of naturally valued places
    		
			"http://mytoursrilanka.eway.asia.lk/images/stories/hikkaduwa.jpg",
			"http://mytoursrilanka.eway.asia.lk/images/stories/lakshapanafalls.jpg",
			"http://mytoursrilanka.eway.asia.lk/images/stories/nilaveli.jpg",
			"http://mytoursrilanka.eway.asia.lk/images/stories/knuckles.jpg"
    };
	
	private String[] historicalImageDesc={		//Descriptions of historically valued places
					"http://mytoursrilanka.eway.asia.lk/index2.php?option=com_content&view=article&id=7&Itemid=7",
		    		"http://mytoursrilanka.eway.asia.lk/index2.php?option=com_content&view=article&id=8&Itemid=8",
		    	    "http://mytoursrilanka.eway.asia.lk/index2.php?option=com_content&view=article&id=9&Itemid=9",
		    	    "http://mytoursrilanka.eway.asia.lk/index2.php?option=com_content&view=article&id=11&Itemid=11",
		    		"http://mytoursrilanka.eway.asia.lk/index2.php?option=com_content&view=article&id=10&Itemid=10"
		    		
	};
	
	private String[] entertainmentImageDesc={		//Descriptions of entertaining places
			"http://mytoursrilanka.eway.asia.lk/index2.php?option=com_content&view=article&id=12&Itemid=12",
    		"http://mytoursrilanka.eway.asia.lk/index2.php?option=com_content&view=article&id=13&Itemid=13",
    		"http://mytoursrilanka.eway.asia.lk/index2.php?option=com_content&view=article&id=14&Itemid=14",
    	    "Bhttp://mytoursrilanka.eway.asia.lk/index2.php?option=com_content&view=article&id=15&Itemid=15"
    		
};
	
	private String[] naturalImageDesc={			//Descriptions of naturally valued places
						
			"http://mytoursrilanka.eway.asia.lk/index2.php?option=com_content&view=article&id=20&Itemid=20",
    		
    		"http://mytoursrilanka.eway.asia.lk/index2.php?option=com_content&view=article&id=17&Itemid=17",
    				
    	    "http://mytoursrilanka.eway.asia.lk/index2.php?option=com_content&view=article&id=18&Itemid=18",
    	    
    	    "http://mytoursrilanka.eway.asia.lk/index2.php?option=com_content&view=article&id=16&Itemid=16"
    		
};
	
	public String[] histroicallyValued = {
			"anuradhapura","polonnaruwa","daladamaligawa","koneshwaramtemple","dambuluviharaya"
	};
	public String[] entertainmentValued = {
			"arugambay","bolgodalake","hanwellarocks","kithulgala"
	};
	public String[] naturallyValued = {
			"hikkaduwa","laxapana","nilavelibeach","knuckles"
	};
	
	
	public static Integer[] objArrayConcat(Integer[] o1, Integer[] o2)		//method to integrate preferences
	 {
		 Integer[] ret = new Integer[o1.length + o2.length];
	  
	   System.arraycopy(o1, 0, ret, 0, o1.length);
	   System.arraycopy(o2, 0, ret, o1.length, o2.length);
	  
	   return ret;
	 }
	
	/**
	 * 
	 * @param o1 first array to be concatenated
	 * @param o2 second array to be concatenated
	 * @return concatenated array
	 */
	public static String[] objArrayConcat(String[] o1, String[] o2)		//method to integrate preferences
	 {
		 String[] ret = new String[o1.length + o2.length];
	  
	   System.arraycopy(o1, 0, ret, 0, o1.length);
	   System.arraycopy(o2, 0, ret, o1.length, o2.length);
	  
	   return ret;
	 }
	
	TextView tx;
	
	public void onCreate(Bundle screen2) {
        super.onCreate(screen2);
        setContentView(R.layout.opengallery);
        
        ArrayList<String> list = new ArrayList<String>();
        list = (ArrayList<String>)getIntent().getExtras().getStringArrayList("preferences");
        
        Toast.makeText(OpenGallery.this, list.toString(), Toast.LENGTH_SHORT).show();
        	if(list.contains("historical")){								//if historical places are preferred
        	finalGallery = (String[])objArrayConcat(finalGallery, historicalImageNames);
        	finalGalleryDesc = (String[])objArrayConcat(finalGalleryDesc, historicalImageDesc);
        	selectedPlacesArray = (String[])objArrayConcat(selectedPlacesArray, histroicallyValued);
        	}
        	
        	if(list.contains("entertainment")){								//if entertainment places are preferred
            	finalGallery = (String[])objArrayConcat(finalGallery, entertainmentImageNames);
            	finalGalleryDesc = (String[])objArrayConcat(finalGalleryDesc, entertainmentImageDesc);
            	selectedPlacesArray = (String[])objArrayConcat(selectedPlacesArray, entertainmentValued);
            }
        	
        	if(list.contains("natural")){								//if naturally beautiful places are preferred
            	finalGallery = (String[])objArrayConcat(finalGallery, naturalImageNames);
            	finalGalleryDesc = (String[])objArrayConcat(finalGalleryDesc, naturalImageDesc);
            	selectedPlacesArray = (String[])objArrayConcat(selectedPlacesArray, naturallyValued);
            }
        	
        Gallery gallery = (Gallery) findViewById(R.id.gallery);			//the gallery view
        gallery.setAdapter(new ImageAdapter(this));
       
        gallery.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(@SuppressWarnings("rawtypes") AdapterView parent, View v, final int position, long id) {
            	
            	WebView picture = (WebView) findViewById(R.id.webview);		//load the clicked image to see it bigger
           		WebSettings webSettings = picture.getSettings();
           		webSettings.setJavaScriptEnabled(true);
           		
           		WebView picture_desc = (WebView) findViewById(R.id.webview_desc);
           		WebSettings webSettingsForDesc = picture_desc.getSettings();
           		webSettingsForDesc.setJavaScriptEnabled(true);
           		
           		picture.loadUrl(finalGallery[position]);
           		picture_desc.loadUrl(finalGalleryDesc[position]);
            	
                Button selectButton = (Button) findViewById(R.id.add_this);
                selectButton.setOnClickListener(new OnClickListener() {

        			@SuppressWarnings("unchecked")
					public void onClick(View v) {
        				selectedPlacesList.add(selectedPlacesArray[position]);		//add the place to an arraylist
        			}
                	
                });
            }
        });
        
        final Button done = (Button) findViewById(R.id.done_selection);
        done.setOnClickListener(new OnClickListener() {

			@SuppressWarnings("unchecked")
			public void onClick(View v) {
				if(selectedPlacesList.size() != 0){
				Intent i = new Intent(v.getContext(),MapRouteActivity.class);
				
				i.putStringArrayListExtra("selected", (ArrayList<String>)selectedPlacesList);
	            startActivity(i);
	            Toast.makeText(OpenGallery.this, "Values are assuming a speed of 110km/h.", Toast.LENGTH_SHORT).show();
				}
				else{
					Toast.makeText(OpenGallery.this, "Please select places to continue", Toast.LENGTH_SHORT).show();
				}
			}
        	
        });
        
        
        
	
	}
	public class ImageAdapter extends BaseAdapter {
	    int mGalleryItemBackground;
	    private Context mContext;
	    int imageBackground;

	    public ImageAdapter(Context c) {
	        mContext = c;
	        TypedArray attr = mContext.obtainStyledAttributes(R.styleable.HelloGallery);
	        mGalleryItemBackground = attr.getResourceId(
	                R.styleable.HelloGallery_android_galleryItemBackground, 1);
	        attr.recycle();
	    }

	    public int getCount() {
	        return finalGallery.length;
	    }

	    public Object getItem(int position) {
	        return position;
	    }

	    public long getItemId(int position) {
	        return position;
	    }
	    
	    public View getView(int position, View convertView, ViewGroup parent) {
            i = new ImageView(this.mContext);
 
            try {
                                /* Open a new URL and get the InputStream to load data from it. */
                                URL aURL = new URL(finalGallery[position]);
                                URLConnection conn = aURL.openConnection();
                                conn.connect();
                                InputStream is = conn.getInputStream();
                                /* Buffered is always good for a performance plus. */
                                BufferedInputStream bis = new BufferedInputStream(is);
                                /* Decode url-data to a bitmap. */
                                Bitmap bm = BitmapFactory.decodeStream(bis);
                                /* Apply the Bitmap to the ImageView that will be returned. */
                                i.setImageBitmap(bm);
                        } catch (IOException e) {
                        }
           
            /* Image should be scaled as width/height are set. */
            i.setScaleType(ImageView.ScaleType.FIT_CENTER);
            /* Set the Width/Height of the ImageView. */
            i.setLayoutParams(new Gallery.LayoutParams(150, 150));
            return i;
        }
	    public float getScale(boolean focused, int offset) {
            /* Formula: 1 / (2 ^ offset) */
        return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset)));
    }
	    
	}
}
